package com.glut.campusrepair.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.glut.campusrepair.config.QueryPageParam;
import com.glut.campusrepair.config.Result;
import com.glut.campusrepair.dto.UserDto;
import com.glut.campusrepair.service.EmailService;
import com.glut.campusrepair.service.IUsersService;
import com.glut.campusrepair.entity.Users;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/users")
public class UsersController {

    @Autowired
    private IUsersService userService;

    @Autowired
    private EmailService emailService;

    private Map<String, String> verificationCodes = new HashMap<>();
    private Map<String, Long> verificationCodeTimes = new HashMap<>();

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody Map<String, String> loginRequest) {
        String username = loginRequest.get("username");
        String password = loginRequest.get("password");

        Users user = userService.getOne(new QueryWrapper<Users>().eq("user_no", username).eq("password", password));
        Map<String, Object> response = new HashMap<>();
        if (user != null) {
            response.put("success", true);
            response.put("message", "登录成功");
            response.put("user", user);
        } else {
            response.put("success", false);
            response.put("message", "用户名或密码错误");
        }
        return response;
    }


    @GetMapping("/me")
    public Map<String, Object> getUserInfo(@RequestParam Integer userId) {
        Users user = userService.getById(userId);
        Map<String, Object> response = new HashMap<>();
        if (user != null) {
            response.put("success", true);
            response.put("user", user);
        } else {
            response.put("success", false);
            response.put("message", "用户信息获取失败");
        }
        return response;
    }

    @PostMapping("/update")
    public Map<String, Object> updateUser(@RequestBody Users user) {
        user.setUpdateTime(new Date());
        boolean success = userService.updateById(user);
        Map<String, Object> response = new HashMap<>();
        if (success) {
            // 返回更新后的用户信息
            Users updatedUser = userService.getById(user.getUserId());
            response.put("success", true);
            response.put("user", updatedUser);
        } else {
            response.put("success", false);
            response.put("message", "用户信息更新失败");
        }
        return response;
    }

    @PostMapping("/forgot-password")
    public Map<String, String> forgotPassword(@RequestBody Map<String, String> request) {
        String username = request.get("username");
        String email = request.get("email");

        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_no", username).eq("email", email);
        Users user = userService.getOne(queryWrapper);

        Map<String, String> response = new HashMap<>();
        if (user == null) {
            response.put("message", "用户不存在或邮箱不匹配");
            return response;
        }

        String code = String.valueOf(new Random().nextInt(899999) + 100000);
        verificationCodes.put(username, code);
        verificationCodeTimes.put(username, System.currentTimeMillis());
        boolean emailSent = emailService.sendResetPasswordEmail(email, code);

        if (emailSent) {
            response.put("message", "验证码已发送到您的邮箱");
        } else {
            response.put("message", "验证码发送失败，请稍后重试");
        }
        return response;
    }

    @PostMapping("/verify-code")
    public Map<String, String> verifyCode(@RequestBody Map<String, String> request) {
        String username = request.get("username");
        String code = request.get("code");

        Map<String, String> response = new HashMap<>();
        String storedCode = verificationCodes.get(username);
        Long sendTime = verificationCodeTimes.get(username);

        if (storedCode != null && storedCode.equals(code)) {
            if (System.currentTimeMillis() - sendTime < 5 * 60 * 1000) {
                response.put("message", "验证成功");
                verificationCodes.remove(username);
                verificationCodeTimes.remove(username);
            } else {
                response.put("message", "验证码已过期");
            }
        } else {
            response.put("message", "验证码错误或已过期");
        }
        return response;
    }

    @PostMapping("/reset-password")
    public Map<String, String> resetPassword(@RequestBody Map<String, String> request) {
        String username = request.get("username");
        String newPassword = request.get("newPassword");

        Map<String, String> response = new HashMap<>();
        Users user = userService.getOne(new QueryWrapper<Users>().eq("user_no", username));

        if (user != null) {
            user.setPassword(newPassword);
            user.setUpdateTime(new Date());
            userService.updateById(user);
            response.put("message", "重置成功");
        } else {
            response.put("message", "用户不存在");
        }
        return response;
    }

    @PostMapping("/register")
    public Map<String, Object> register(@RequestBody Map<String, String> registerRequest) {
        String username = registerRequest.get("username");
        String password = registerRequest.get("password");
        String name = registerRequest.get("name");
        String userType = registerRequest.get("userType");

        Map<String, Object> response = new HashMap<>();

        if (!username.matches("^[0-9]+$")) {
            response.put("success", false);
            response.put("message", "用户名只能包含纯数字");
            return response;
        }

        Users existingUser = userService.getOne(new QueryWrapper<Users>().eq("user_no", username));
        if (existingUser != null) {
            response.put("success", false);
            response.put("message", "用户名已存在");
            return response;
        }

        Users user = Users.builder()
                .userNo(username)
                .name(name)
                .type(userType)
                .password(password)
                .createTime(new Date())
                .updateTime(new Date())
                .build();

        userService.save(user);

        response.put("success", true);
        response.put("message", "注册成功");
        return response;
    }




    //linghu

    @Autowired
    private IUsersService usersService; // 注入用户服务

    /**
     * 获取所有用户信息
     * @return 所有用户信息
     */
    @GetMapping("/list")
    public List<Users> getAllUsers() {
        return usersService.list();
    }

    /**
     * 新增用户
     * @param users 用户信息
     */
    @PostMapping("/save")
    public boolean addUser(@RequestBody Users users) {
        return usersService.save(users);
    }
    /**
     * 修改用户
     * @param users 用户信息
     */
    @PostMapping("/mod")
    public boolean modUser(@RequestBody Users users) {
        return usersService.updateById(users);
    }
    /**
     * 新增或修改用户
     * @param users 用户信息
     */
    @PostMapping("/saveOrMod")
    public boolean saveOrMod(@RequestBody Users users) {
        return usersService.saveOrUpdate(users);
    }

    /**
     * 删除用户
     * @param id 用户id
     */
//    @DeleteMapping("/delete/{id}")
//    public boolean deleteUser(@PathVariable Integer id) {
//        return usersService.removeById(id);
//    }
    @GetMapping("/delete")
    public boolean deleteUser(@RequestParam("user_id")Integer id) {
        return usersService.removeById(id);
    }

    /**
     * 模糊查询用户
     *
     * @param user 用户信息
     */
    @PostMapping("/ListP")
    public List<Users> ListP(@RequestBody Users user){
        LambdaQueryWrapper<Users> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(Users::getName,user.getName());
        //.eq(Users::getName,user.getName());表示完全匹配
        return usersService.list(lambdaQueryWrapper);
    }


    /**
     *  分页查询用户人员,下面这个方法是Ipage的分页查询方法，相关方法只需要调用
     *  通过查询用户的名字进行分页
     */

    @PostMapping("/listUsersPage")
    public Result listUsersPage(@RequestBody QueryPageParam query) {

        HashMap<String, Object> param = query.getParam();

        String name = (String) param.get("name");
        String user_no = (String) param.get("user_no");

        // 设置分页
        Page<Users> page = new Page<>(query.getPageNum(), query.getPageSize());

        // 构建查询条件
        LambdaQueryWrapper<Users> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (name != null && !name.isEmpty()) {
            lambdaQueryWrapper.like(Users::getName, name);
        }
        if (user_no != null && !user_no.isEmpty()) {
            lambdaQueryWrapper.like(Users::getUserNo, user_no);
        }

        // 获取查询结果
        IPage<Users> result = usersService.page(page, lambdaQueryWrapper);
        System.out.println("total==" + result.getTotal());

        // 返回结果
        return Result.success(result.getRecords(), result.getTotal());
    }



    @PostMapping("/listUsersPage1")
    public Result listUsersPage1(@RequestBody QueryPageParam query) {

        HashMap<String, Object> param = query.getParam();

        String name = (String) param.get("name");
        String userNo = (String) param.get("userNo");
        String type = (String) param.get("type");
        String grade = (String) param.get("grade");
        String dormGroup = (String) param.get("dormGroup");
        String dormBuilding = (String) param.get("dormBuilding");

        // 设置分页
        Page<Users> page = new Page<>(query.getPageNum(), query.getPageSize());

        // 构建查询条件
        LambdaQueryWrapper<Users> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        if (name != null && !name.isEmpty()) {
            lambdaQueryWrapper.like(Users::getName, name);
        }
        if (userNo != null && !userNo.isEmpty()) {
            lambdaQueryWrapper.like(Users::getUserNo, userNo);
        }
        if (type != null && !type.isEmpty()) {
            lambdaQueryWrapper.like(Users::getType, type);
        }
        if (grade != null && !grade.isEmpty()) {
            lambdaQueryWrapper.like(Users::getGrade, grade);
        }
        if (dormGroup != null && !dormGroup.isEmpty()) {
            lambdaQueryWrapper.like(Users::getDormGroup, dormGroup);
        }
        if (dormBuilding != null && !dormBuilding.isEmpty()) {
            lambdaQueryWrapper.like(Users::getDormBuilding, dormBuilding);
        }

        // 获取查询结果
        IPage<Users> result = usersService.page(page, lambdaQueryWrapper);
        System.out.println("total==" + result.getTotal());

        // 返回结果
        return Result.success(result.getRecords(), result.getTotal());
    }


    /**
     * 批量删除用户
     *
     * @param userDto 包含要删除的用户ID列表
     * @return 是否删除成功
     */
    @PostMapping("/deleteBatch")
    public boolean deleteBatch(@RequestBody UserDto userDto) {
        List<Integer> ids = userDto.getUserIdList();
        return userService.removeByIds(ids);
    }



}
